package com.aaron.kjviewutils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.aaron.kjviewutils.eventBus.EventBusMsg;
import com.aaron.kjviewutils.retrofit.RetrofitUtil;
import com.aaron.kjviewutils.spinkit.ProgressPopupWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import retrofit2.Retrofit;

/**
 * 作者：Aaron on 2017/2/14 09:54
 * 邮箱：kaijin.fang@edianniu.com
 */
public class BaseActivity extends AppCompatActivity {

    public BaseApplication application;
    public Resources resources;
    public WindowManager windowManager;
    public Handler mHandler;
    public Retrofit retrofit;
    public EventBus eventBus;
    private NetStatusReceiver netStatusReceiver;
    public ProgressPopupWindow progress;
    public LayoutInflater inflater;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        application = (BaseApplication) BaseActivity.this.getApplication();
        resources = this.getResources();
        windowManager = this.getWindowManager();
        mHandler = new Handler();
        inflater = LayoutInflater.from(BaseActivity.this);
        eventBus = EventBus.getDefault();
        eventBus.register(BaseActivity.this);
        retrofit = RetrofitUtil.obtainRetrofit();
        progress = new ProgressPopupWindow(BaseActivity.this, BaseActivity.this);
        //禁止横屏
        BaseActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //监测网络
        netStatusReceiver = new NetStatusReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        BaseActivity.this.registerReceiver(netStatusReceiver, filter);
    }

    @SuppressLint("NewApi")
    public void loadBackground(View view, Drawable drawable)
    {
        if(getSDKVersion() >= 16)
        {
            view.setBackground(drawable);
        }
        else
        {
            view.setBackgroundDrawable(drawable);
        }
    }

    public void showActivity(Activity aty , Class clazz , Bundle bundle ){
        Intent i = new Intent(aty, clazz);
        i.putExtras(bundle);
        aty.startActivity(i);
    }

    public void showActivity(Activity aty , Class clazz ){
        Intent i = new Intent(aty, clazz);
        aty.startActivity(i);
    }

    public void closeSelf(Activity aty)
    {
        aty.finish();
    }

    public void killAppDestory(Context context)
    {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //2.2之前操作
        if(8 < getSDKVersion())
        {
            am.restartPackage(context.getPackageName());
        }
        else if(8<=getSDKVersion())
        {
            am.killBackgroundProcesses(context.getPackageName());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
    public void onEvent(EventBusMsg msg)
    {
        switch (msg.getType())
        {
            case NET_CHECK:
            {
                Toast.makeText(BaseActivity.this, "网络已断开", Toast.LENGTH_SHORT).show();
            }
            break;
            default:
                break;
        }
    }

    /**
     * 获取手机系统SDK版本
     *
     * @return 如API 17 则返回 17
     */
    public int getSDKVersion() {
        return android.os.Build.VERSION.SDK_INT;
    }

    public class NetStatusReceiver extends BroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION))
            {
                if(!checkNet(context))
                {
                    //没有网络
                    eventBus.post(new EventBusMsg(EventBusMsg.EventBusType.NET_CHECK));
                }
            }
        }
    }

    /**
     * 判断网络是否连接
     */
    public static boolean checkNet(Context context)
    {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        return info != null;// 网络是否连接
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null!=progress)
        {
            progress.dismissView();
        }
        if(null!=eventBus)
        {
            eventBus.unregister(BaseActivity.this);
        }
        if(null!=netStatusReceiver)
        {
            BaseActivity.this.unregisterReceiver(netStatusReceiver);
        }
    }

    public String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
            return stringBuilder.toString();
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public int dp2px(float dpValue) {
        float scale = resources.getDisplayMetrics().density;
        return (0==dpValue)?0:(int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public int px2dp(float pxValue) {
        float scale = resources.getDisplayMetrics().density;
        return (0==pxValue)?0:(int) (pxValue / scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 sp 的单位 转成为 px(像素)
     */
    public int sp2px(float sp) {
        float scale = resources.getDisplayMetrics().density;
        return (0==sp)?0:(int) (sp * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 sp
     */
    public int px2sp(float px) {
        float scale = resources.getDisplayMetrics().density;
        return (0==px)?0:(int) Math.ceil(px / scale);
    }

    /**
     * 根据手机的分辨率从 sp 的单位 转成为 dp
     */
    public int sp2dp(float sp) {
        float scale = resources.getDisplayMetrics().density;
        return (0==sp)?0:px2dp(sp2px(sp));
    }

    /**
     * 根据手机的分辨率从 dp(像素) 的单位 转成为 ps
     */
    public int dp2sp(float dp) {
        float scale = resources.getDisplayMetrics().density;
        return (0==dp)?0:px2sp(dp2px(dp));
    }

    public void saveCitys(String provde, String city)
    {
        PreferenceHelper.writeString(BaseActivity.this, "citys", "provde", provde);
        PreferenceHelper.writeString(BaseActivity.this, "citys", "city", city);
    }

    public String[] obtainCitys()
    {
        String[] citys = {PreferenceHelper.readString(BaseActivity.this, "citys", "provde"), PreferenceHelper.readString(BaseActivity.this, "citys", "city")};
        return citys;
    }

    public void saveAccount(AccountBean account)
    {
        if(null!=account.result)
        {
            PreferenceHelper.writeString(BaseActivity.this, "account", "uid", account.result.uid);
            PreferenceHelper.writeString(BaseActivity.this, "account", "username", account.result.username);
            PreferenceHelper.writeString(BaseActivity.this, "account", "password", account.result.password);
            PreferenceHelper.writeString(BaseActivity.this, "account", "email", account.result.email);
            PreferenceHelper.writeString(BaseActivity.this, "account", "token", account.result.token);
            PreferenceHelper.writeString(BaseActivity.this, "account", "item", account.result.item);
            PreferenceHelper.writeString(BaseActivity.this, "account", "value", account.result.value);
        }
    }

    public void saveUid(String uid)
    {
        PreferenceHelper.writeString(BaseActivity.this, "account", "uid", uid);
    }

    public String obtainToken()
    {
        return PreferenceHelper.readString(BaseActivity.this, "account", "token");
    }

    public static void backgroundAlpha(Activity aty, float alpha)
    {
        WindowManager.LayoutParams lp = aty.getWindow ().getAttributes ();
        lp.alpha = alpha;
        aty.getWindow ().setAttributes ( lp );
    }

    public void showMsg(String msg)
    {
        Toast.makeText(BaseActivity.this, msg, Toast.LENGTH_SHORT).show();
    }

    public String obtainToday(String formatStr)
    {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat(formatStr);
        return format.format(date);
    }

    public String obtainToday(Date date, String formatStr)
    {
        DateFormat format = new SimpleDateFormat(formatStr);
        return format.format(date);
    }

    public String[] PERMISSION = {
            Manifest.permission.GET_ACCOUNTS,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };
}
